﻿$(function () {
    $(window).scroll(function () {
        var scrollVal = $(window).scrollTop();
        //置顶显示
        if (scrollVal > 200) {
            if ($(".pagetotop").is(':hidden')) {
                $(".pagetotop").show();
            }
        } else {
            $(".pagetotop").hide();
        }
    });

    //小屏幕时，显示菜单按钮
    $(".btnMenu,.btnMenu2,.mask").click(function () {
        $("body").toggleClass("active")
    });
    //模式切换
    $("#changStyle").click(function () {
        $("html").toggleClass("night");
        isNightStyle.change();
    })

    $(".user-history h3").click(function () {
        $("#historyList").toggle();
    })
    userHistory.showHistory();
})

var userHistory = {
    fetch: function () {
        return JSON.parse(localStorage.getItem("history") || '[]');
    },
    save: function (todos) {
        localStorage.setItem("history", JSON.stringify(todos));
    },
    additem: function (todo) {
        if (!userHistory.isExist(todo)) {
            var todoList = userHistory.fetch();
            //判断数组里面有么有，没有则加入
            todoList.unshift(todo);
            //如果浏览记录超过10条，去掉最老的一条
            if (todoList.length > 10)
                todoList.pop();
            localStorage.setItem("history", JSON.stringify(todoList));
        }
    },
    isExist: function (todo) {
        var todoList = userHistory.fetch();
        var exist = false;
        todoList.forEach(function (item) {
            if (item.chapterid == todo.chapterid)
                exist = true;
        })
        return exist;
    },
    showHistory:function(){
        var list = userHistory.fetch();
        var temp="";
        list.forEach(function (item) {
            temp += "<li><a href=\"/book/Chapter/" + item.bookid + "/" + item.chapterid + "\">";
            temp += item.bookname + "" + item.chapterName;
            temp += "</a></li>";
        })
        $("#historyList").html(temp);
    }
}

var isNightStyle=
{
    get: function () {
        return getCookie("htmlstyle") || "";
    },
    set: function (v) {
        setCookie("htmlstyle", v);
    },
    change: function () {
        if (isNightStyle.get())
            isNightStyle.set('');
        else
            isNightStyle.set('night');
    }
}


//写cookies
function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
}
//读取cookies
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}